package org.jie.guider.java.base.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LiJie
 */
public class Thread_Object_Lock {

    private final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread_Object_Lock tol = new Thread_Object_Lock();
        new Thread(tol::A).start();
        new Thread(() -> tol.B(null)).start();
    }

    public synchronized void A() {
        System.out.println("method A");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException ignore) {
        }
        B("A");
    }

    public synchronized void B(String flag) {
        System.out.println("method B " + flag);
    }

    public void ALock() {
        try {
            lock.lock();
            System.out.println("method A");
            TimeUnit.SECONDS.sleep(5);
            B("A");
        } catch (InterruptedException ignore) {
        } finally {
            lock.unlock();
        }
    }

    public void BLock(String flag) {
        lock.lock();
        System.out.println("method B-lock " + flag);
        lock.unlock();
    }
}